package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLHouseDBManager;
import com.qiantu.api.entity.HouseBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.exception.ResultException;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.RefreshHouseEvent;
import com.qiantu.phone.ui.dialog.ConfirmCancelHintDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import okhttp3.Call;

public class HomeManagerActivity extends AppActivity {
    private final int EDIT_HOUSE_CODE = 0x1;
    private final int ADD_HOUSE_CODE = 0x2;
    private TextView mHomeName;
    private TextView mHomeLocation;
    private ImageView mHomeEdit;
    private TextView mRoomManager;
    private TextView mMemberManager;
    private TextView mHouseTransfer;
    private TextView mDeleteHouse;
    private TextView mVRoleType;
    private RecyclerView mOtherHouseList;
    private View mCurHouseLy;
    private HouseAdapter houseAdapter;
    private HouseBean curHouseInfo;
    private List<HouseBean> houses;
    private View mQuitHouse;
    private int mType;//1.正常启动，2.当前房屋被删除了，跳转到房屋选择界面

    @Log
    public static void start(Context context, int type) {
        Intent intent = new Intent(context, HomeManagerActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mType = getIntent().getIntExtra("type", 1);
        mCurHouseLy = findViewById(R.id.cur_house_ly);
        mHomeName = findViewById(R.id.home_name);
        mHomeLocation = findViewById(R.id.home_location);
        mHomeEdit = findViewById(R.id.home_edit);
        mRoomManager = findViewById(R.id.room_manager);
        mMemberManager = findViewById(R.id.member_manager);
        mHouseTransfer = findViewById(R.id.house_transfer);
        mDeleteHouse = findViewById(R.id.delete_house);
        mOtherHouseList = findViewById(R.id.other_house_list);
        mQuitHouse = findViewById(R.id.quit_house);
        mVRoleType = findViewById(R.id.roleType);
        setOnClickListener(mHouseTransfer, mHomeEdit, mRoomManager, mMemberManager, mQuitHouse, mHouseTransfer, mDeleteHouse, mVRoleType);
        houseAdapter = new HouseAdapter();
        mOtherHouseList.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        mOtherHouseList.setAdapter(houseAdapter);
        houseAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                HouseBean houseBean = houseAdapter.getData().get(position);
                showConfirmCancelHintDialog(getString(R.string.change_house_hint, houseBean.getName()), "取消", "切换", new ConfirmCancelHintDialog.OnListener() {
                    @Override
                    public void onLeftClick(BaseDialog dialog) {
                        dialog.dismiss();
                    }

                    @Override
                    public void onRightClick(BaseDialog dialog) {
                        dialog.dismiss();
                        String loginToken = null;
                        if(AppApplication.getInstance().getLoginInfo() != null){
                            loginToken = AppApplication.getInstance().getLoginInfo().getToken();
                        }
                        LLHttpManager.editDefaultHouse(HomeManagerActivity.this, loginToken, houseBean.getHouseSerialNo(), new HttpCallback<HttpData<Void>>(HomeManagerActivity.this) {
                            @Override
                            public void onStart(Call call) {
                                showDialog(getString(R.string.switching_houses));
                            }

                            @Override
                            public void onSucceed(HttpData<Void> result) {
                                AppApplication.getInstance().setCurHouseInfo(houseBean);
                                AppApplication.getInstance().changeHouseData((AppActivity) getActivity(), getString(R.string.switching_houses));
                            }

                            @Override
                            public void onFail(Exception e) {
                                if (e instanceof ResultException){
                                    int errorCode = ((ResultException)e).getHttpData().getCode();
                                    if(errorCode == 10401){//登录过期
                                        AppApplication.getInstance().handleError401();
                                    }else if(errorCode == 90007){//房屋权限失效
                                        //删除切换的房屋
                                        LLHouseDBManager.getInstance(getContext()).remove(houseBean.getHouseSerialNo());
                                        ToastUtils.show("您切换的房屋不存在或没有权限");
                                        updateView();
                                    }else if(errorCode == 90010){//账号已注销
                                        AppApplication.getInstance().handleError90010();
                                    }else {
                                        super.onFail(e);
                                    }
                                }else {
                                    super.onFail(e);
                                }
                            }

                            @Override
                            public void onEnd(Call call) {
                                hideDialog();
                            }
                        });
                    }
                });
            }
        });
        if (mType == 2){
            mCurHouseLy.setVisibility(View.GONE);
            getTitleBar().getLeftView().setVisibility(View.GONE);
        }
        updateView();
    }

    private void updateView(){
        houses = LLHouseDBManager.getInstance(this).getAll();
        if(houses == null || houses.size() == 0){
            return;
        }
        curHouseInfo = AppApplication.getInstance().getCurHouseInfo();
        if (curHouseInfo != null) {
            //从本地数据拿下最新的数据，有可能房屋被别人删除获取修改，后台进前台刷新了本地数据库
            curHouseInfo = LLHouseDBManager.getInstance(this).getHouseByHouseSerialNo(curHouseInfo.getHouseSerialNo());
            if(curHouseInfo == null){
                curHouseInfo = houses.get(0);
            }
            mHomeName.setText(curHouseInfo.getName());
            mHomeLocation.setText(curHouseInfo.getAddress());
        } else {
            curHouseInfo = houses.get(0);
        }
        if (curHouseInfo != null) {
            mHomeName.setText(curHouseInfo.getName());
            mHomeLocation.setText(curHouseInfo.getAddress());
            mVRoleType.setText(getRoleType(curHouseInfo.getRoleType()));
            setRoleView(curHouseInfo.getRoleType());
        }
        houseAdapter.setNewInstance(removeDefaultHouse(houses));
        setVisibilityBind(R.id.other_house_title, houseAdapter.getData().isEmpty()? View.GONE : View.VISIBLE);
    }

    private String getRoleType(int type){
        String result = getString(R.string.huzhu);
        if (type == 0){
            result = getString(R.string.huzhu);
        }else if (type == 1){
            result = getString(R.string.guanliyuan);
        }else if(type == 2){
            result = "普通成员";
        }
        return result;
    }

    private void setRoleView(int type){
        if (type == 0){
            mHouseTransfer.setVisibility(View.VISIBLE);
            mDeleteHouse.setVisibility(View.VISIBLE);
            mQuitHouse.setVisibility(View.GONE);
            mHomeEdit.setVisibility(View.VISIBLE);
        }else if (type == 1){
            mHouseTransfer.setVisibility(View.GONE);
            mDeleteHouse.setVisibility(View.GONE);
            mQuitHouse.setVisibility(View.VISIBLE);
            mHomeEdit.setVisibility(View.VISIBLE);
        }else{
            mHouseTransfer.setVisibility(View.GONE);
            mDeleteHouse.setVisibility(View.GONE);
            mQuitHouse.setVisibility(View.VISIBLE);
            mHomeEdit.setVisibility(View.GONE);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshHouseEvent(RefreshHouseEvent event) {
        updateView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home_manager;
    }

    @Override
    protected void initView() {
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    public List<HouseBean> removeDefaultHouse(List<HouseBean> data) {
        if (data == null || data.isEmpty()) return null;
        if (curHouseInfo == null || TextUtils.isEmpty(curHouseInfo.getHouseSerialNo())) {
            data.remove(0);
            return data;
        }
        for (HouseBean bean : data) {
            if (curHouseInfo.getHouseSerialNo().equals(bean.getHouseSerialNo())) {
                data.remove(bean);
                return data;
            }
        }
        return null;
    }

    @Override
    public void onClick(View view) {
        if (view == mHomeEdit) {
            Intent intent = new Intent(getContext(), HouseEditActivity.class);
            startActivityForResult(intent, EDIT_HOUSE_CODE);
        } else if (view == mRoomManager) {
            RoomManagementActivity.start(this);
        } else if (view == mMemberManager) {
            startActivity(MemberManagerActivity.class);
        } else if (view == mHouseTransfer) {
            startActivity(HouseTransferActivity.class);
        } else if (view == mDeleteHouse) {
            //房屋里有主机时，不能删除房屋
            if(LLControllerDBManager.getInstance(this).hasHostController()){
                ToastUtils.show(R.string.house_has_host_device_hint);
                return;
            }
            //等待被过户的房屋无法被删除
            if(curHouseInfo.getType() == 1){
                ToastUtils.show(R.string.transferring_house_delete_hint);
                return;
            }
             if(houses.size() == 0){
                ToastUtils.show(R.string.house_delete_nohouse_hint);
                return;
            }
            showConfirmCancelHintDialog(getString(R.string.delete_house_hint), getString(R.string.cancel), getString(R.string.delete), new ConfirmCancelHintDialog.OnListener() {
                @Override
                public void onLeftClick(BaseDialog dialog) {
                    dialog.dismiss();
                }

                @Override
                public void onRightClick(BaseDialog dialog) {
                    dialog.dismiss();
                    LLHttpManager.deleteHouse((LifecycleOwner) getActivity(), curHouseInfo.getHouseSerialNo(), new HttpCallback<HttpData<Void>>((OnHttpListener) getActivity()) {
                        @Override
                        public void onStart(Call call) {
                            showDialog(getString(R.string.deleting_houses));
                        }

                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            toast(R.string.delete_success);
//                            LLHouseDBManager.getInstance(getContext()).remove(curHouseInfo.getHouseSerialNo());
//                            AppApplication.getInstance().removeCurrentHouse();
                            //删除房屋后，切换房屋获取列表第一个房屋数据
                            AppApplication.getInstance().changeHouseData((AppActivity) getActivity(), true, getString(R.string.switching_houses));
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }

                        @Override
                        public void onEnd(Call call) {
                            hideDialog();
                        }
                    });
                }
            });
        } else if (view == mQuitHouse){
            showConfirmCancelHintDialog(getString(R.string.quit_house_hint), getString(R.string.cancel), getString(R.string.exit), new ConfirmCancelHintDialog.OnListener() {
                @Override
                public void onLeftClick(BaseDialog dialog) {
                    dialog.dismiss();
                }

                @Override
                public void onRightClick(BaseDialog dialog) {
                    dialog.dismiss();
                    LLHttpManager.quitHouse((LifecycleOwner) getActivity(), curHouseInfo.getHouseSerialNo(), new HttpCallback<HttpData<Void>>((OnHttpListener) getActivity()) {
                        @Override
                        public void onStart(Call call) {
                            showDialog(getString(R.string.exiting_house));
                        }

                        @Override
                        public void onSucceed(HttpData<Void> result) {
                            toast(R.string.exit_success);
//                            LLHouseDBManager.getInstance(getContext()).remove(curHouseInfo.getHouseSerialNo());
//                            AppApplication.getInstance().removeCurrentHouse();
                            //删除房屋后，切换房屋获取列表第一个房屋数据
                            AppApplication.getInstance().changeHouseData((AppActivity) getActivity(), true, getString(R.string.switching_houses));
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }

                        @Override
                        public void onEnd(Call call) {
                            hideDialog();
                        }
                    });
                }
            });
        }
    }

    @Override
    public void onRightClick(View view) {
//        FamilyInfoActivity.start(this, 1);
        Intent intent = new Intent(this, FamilyInfoActivity.class);
        intent.putExtra("TYPE", 1);
        startActivityForResult(intent, ADD_HOUSE_CODE);
    }

    private class HouseAdapter extends BaseQuickAdapter<HouseBean, BaseViewHolder> {

        public HouseAdapter() {
            super(R.layout.house_item);
        }

        @Override
        protected void convert(BaseViewHolder helper, HouseBean item) {
            helper.setText(R.id.home_name, item.getName());
            helper.setText(R.id.home_location, item.getAddress());
            helper.setText(R.id.roleType, getRoleType(item.getRoleType()));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == EDIT_HOUSE_CODE) {
                curHouseInfo = AppApplication.getInstance().getCurHouseInfo();
                mHomeName.setText(curHouseInfo.getName());
                mHomeLocation.setText(curHouseInfo.getAddress());
            }
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}